package com.aliyun.heiyu.powermaster.server.rbac.service.impl;
import com.aliyun.heiyu.common.util.*;
import com.aliyun.heiyu.powermaster.proto.*;
import com.aliyun.heiyu.powermaster.server.Constant;
import com.aliyun.heiyu.powermaster.server.Error;
import com.aliyun.heiyu.powermaster.server.annotation.Transactional;
import com.aliyun.heiyu.powermaster.server.dao.entity.EmailPropertiesConfig;
import com.aliyun.heiyu.powermaster.server.dao.enums.UserErrorEnum;
import com.aliyun.heiyu.powermaster.server.rbac.dao.SysAuditManagementsDao;
import com.aliyun.heiyu.powermaster.server.rbac.dao.SysSafeDAO;
import com.aliyun.heiyu.powermaster.server.rbac.dao.TokenMangerDao;
import com.aliyun.heiyu.powermaster.server.rbac.dao.impl.SysAuditManagementsDaoImpl;
import com.aliyun.heiyu.powermaster.server.rbac.dao.impl.SysSafeDAOImpl;
import com.aliyun.heiyu.powermaster.server.rbac.dao.impl.TokenMangerDaoImpl;
import com.aliyun.heiyu.powermaster.server.rbac.enums.*;
import com.aliyun.heiyu.powermaster.server.rbac.object.dto.SafeDTO;
import com.aliyun.heiyu.powermaster.server.rbac.object.dto.SafeDataDTO;
import com.aliyun.heiyu.powermaster.server.rbac.object.entity.SysAuditManagements;
import com.aliyun.heiyu.powermaster.server.rbac.object.entity.SysSafeAuditEntity;
import com.aliyun.heiyu.powermaster.server.rbac.service.SafeService;
import com.aliyun.heiyu.powermaster.server.rbac.utils.*;
import com.aliyun.heiyu.powermaster.server.rotary.dao.AirDAO;
import com.aliyun.heiyu.powermaster.server.rotary.dao.impl.AirDAOImpl;
import com.aliyun.heiyu.powermaster.server.util.IscMailBuilder;
import com.aliyun.heiyu.powermaster.server.util.MailSendUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import java.sql.SQLException;
import java.util.*;

public class SafeServiceImpl implements SafeService {
    private static Logger logger = LoggerFactory.getLogger(SafeServiceImpl.class);
    private SysSafeDAO sysSafeDAO;
    private TokenMangerDao tokenManagerDao;
    private SysAuditManagementsDao auditManagementsDao;
    private AirDAO airDAO;
    private int count = 0;
    private int countOver = 0;

    // 操作类型（1-增加 2-删除 3-修改 4-查询 5-导入 6-导出 7-登录 8-登出 9-越权访问 10-登录失效）
    private static final List<Integer> operas = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8,9,10);

    public SafeServiceImpl() {
        this.sysSafeDAO = new SysSafeDAOImpl();
        this.tokenManagerDao = new TokenMangerDaoImpl();
        this.auditManagementsDao = new SysAuditManagementsDaoImpl();
        this.airDAO=new AirDAOImpl();
    }

    @Override
    public boolean insertSysSafeBusiness(SysSafeAuditEntity safeAuditEntity, String token) {
        //判断是否记录查询操作
        String userIp = Constant.USER_IP_KEY.get();
        try {
            if (!StringUtil.isEmpty(userIp)) {
                safeAuditEntity.setIp(userIp);
            }
            Map<String, String> map = tokenManagerDao.findByToken(token);
            if (null != map && map.size() != 0) {
                String data = map.get("data");
                if (!StringUtil.isEmpty(data)) {
                    safeAuditEntity.setUsername(new SM4JSUtil().decode(data));
                }
            }
            //1.默认为业务业务
            if (0 == safeAuditEntity.getEvent_type()) {
                safeAuditEntity.setEvent_type(EventTypeEnum.BUSINESS.getCode());
            }
            //2，默认正常
            if (0 == safeAuditEntity.getEvent_state()) {
                safeAuditEntity.setEvent_state(EventStateEnum.NORMAL.getCode());
            }
            //3.默认成功
            if (EventStateEnum.NORMAL.getCode() == safeAuditEntity.getEvent_state()) {
                safeAuditEntity.setEvent_result(EventResultEnum.SUCCESS.getCode());
            }
            //处理数据
            handleEventState(safeAuditEntity);

            return true;
        } catch (Exception e) {
            return true;
        }
    }

    /**
     *  判断是否要记录查询操作
     * @param operaType 操作，4位查询操作
     * @param username 用户名
     * @return 返回fasle不记录，返回true记录
     */
    private boolean queryRecord(int operaType, String username) {
        if (4 == operaType && !StringUtil.isEmpty(username)){
            SysAuditManagements auditManagement = auditManagementsDao.getAuditManagementByUserName(username);
            if (auditManagement != null && auditManagement.getStartTime() != null && auditManagement.getEndTime() != null){
                Date currentDate = new Date();
                return !currentDate.before(auditManagement.getEndTime()) && currentDate.after(auditManagement.getStartTime());
            }
        }
        return true;
    }


    @Override
    public boolean insertSysSafeSystem(SysSafeAuditEntity safeAuditEntity) {
        try {
            //1.系统事件
            safeAuditEntity.setEvent_type(EventTypeEnum.SYSTEM.getCode());
            //菜单
            safeAuditEntity.setMenu_url("系统");
            //3.成功 - 完成    失败 - 异常
            if (EventStateEnum.NORMAL.getCode() == safeAuditEntity.getEvent_state()) {
                safeAuditEntity.setEvent_result(EventResultEnum.SUCCESS.getCode());
            }else {
                safeAuditEntity.setEvent_result(EventResultEnum.FAIL.getCode());
            }
            //处理数据
            handleEventState(safeAuditEntity);
        }catch (Exception e){
            logger.error(e.getMessage());
        }
       return true;
}
    @Override
    public CommonReply insertSysSafeBusinessToPy(AddSafePyRequest request) {
        CommonReply.Builder builder = CommonReply.newBuilder();
        if (StringUtil.isEmpty(request.getToken())) {
            return builder.setErrCode(Error.SUCCESS.getCode())
                          .setErrMsg(Error.SUCCESS.getMessage())
                          .build();
        }
        //判断是否记录查询操作
        try {
            SysSafeAuditEntity safeAuditEntity = new SysSafeAuditEntity();
            Map<String, String> map = tokenManagerDao.findByToken(request.getToken());
            if (null != map && map.size() != 0) {
                String data = map.get("data");
                if (!StringUtil.isEmpty(data)) {
                    //添加用户名
                    safeAuditEntity.setUsername(new SM4JSUtil().decode(data));
                }
            }
            //添加安全状态 1-异常1   3-正常
            safeAuditEntity.setEvent_state(6);
            //事件结果（1-失败  2-成功）
            safeAuditEntity.setEvent_result(1);
            //记录ip
            if (!StringUtil.isEmpty(request.getIp())) {
                safeAuditEntity.setIp(request.getIp());
            }
            //事件描述
            if(!StringUtil.isEmpty(request.getEventDesc())){
                safeAuditEntity.setEvent_desc(request.getEventDesc());
            }
            //默认为业务业务
            safeAuditEntity.setMenu_url("系统");
            safeAuditEntity.setEvent_type(1);
            if(!safeAuditEntity.getEvent_desc().contains("越权")){
                return builder.setErrCode(Error.SUCCESS.getCode())
                    .setErrMsg(Error.SUCCESS.getMessage())
                    .build();
            }
            safeAuditEntity.setOpera_type(11);
            //处理数据
            handleEventState(safeAuditEntity);
        } catch (Exception e) {
            return builder.setErrCode(Error.FAILED.getCode())
                .setErrMsg(Error.FAILED.getMessage())
                .build();
        }
        return builder.setErrCode(Error.SUCCESS.getCode())
            .setErrMsg(Error.SUCCESS.getMessage())
            .build();
    }



    @Override
    public CommonReply insertSysSafeBusiness(AddSafeRequest request) {
        CommonReply.Builder builder = CommonReply.newBuilder();
        String userIp = Constant.USER_IP_KEY.get();
        AddSafeRequest.Builder newBuilder = request.toBuilder();
        newBuilder.setIp(userIp);
        ThreadPoolUtil.execute(new Runnable() {
            @Override
            public void run() {
                insertSysSafe(newBuilder.build());
            }
        });
        return builder.setErrCode(Error.SUCCESS.getCode())
            .setErrMsg(Error.SUCCESS.getMessage())
            .build();
    }

    public CommonReply insertSysSafe(AddSafeRequest request) {
        CommonReply.Builder builder = CommonReply.newBuilder();
        boolean isQuery = queryRecord(request.getOperaType(),request.getUsername());
        if(!isQuery){
            return builder.setErrCode(Error.SUCCESS.getCode())
                .setErrMsg(Error.SUCCESS.getMessage())
                .build();
        }
        try {
            SysSafeAuditEntity safeAuditEntity = new SysSafeAuditEntity();

            safeAuditEntity.setUsername(request.getUsername());

            //添加安全状态 1-异常1   3-正常
            safeAuditEntity.setEvent_state(request.getEventState());
            //事件结果（1-失败  2-成功）
            if(request.getEventState() == 3){
                safeAuditEntity.setEvent_result(2);
            }else {
                safeAuditEntity.setEvent_result(1);
            }
            //事件描述
            if(!StringUtil.isEmpty(request.getEventDesc())){
                safeAuditEntity.setEvent_desc(request.getEventDesc());
            }
            //菜单路径
            if(!StringUtil.isEmpty(request.getMenuUrl())){
                safeAuditEntity.setMenu_url(request.getMenuUrl());
            }
            //判断是否是正确操作类型
            if(!operas.contains(request.getOperaType())){
                return  builder.setErrCode(963)
                    .setErrMsg("操作类型有误")
                    .build();
            }
            safeAuditEntity.setOpera_type(request.getOperaType());
            if(!StringUtil.isEmpty(request.getIp())){
                safeAuditEntity.setIp(request.getIp());
            }
            //默认为业务业务
            if(request.getEventType() == EventTypeEnum.SYSTEM.getCode()){
                safeAuditEntity.setEvent_type(EventTypeEnum.SYSTEM.getCode());
            }else {
                safeAuditEntity.setEvent_type(EventTypeEnum.BUSINESS.getCode());
            }
            //处理数据
            handleEventState(safeAuditEntity);
        } catch (Exception e) {
            return builder.setErrCode(Error.SUCCESS.getCode())
                .setErrMsg(Error.SUCCESS.getMessage())
                .build();
        }
        return builder.setErrCode(Error.SUCCESS.getCode())
            .setErrMsg(Error.SUCCESS.getMessage())
            .build();
    }


    @Override
    public boolean insertSysSafeBusinessException(SysSafeAuditEntity safeAuditEntity, String token) {

        String userIp = Constant.USER_IP_KEY.get();
        try {
            if (!StringUtil.isEmpty(userIp)) {
                safeAuditEntity.setIp(userIp);
            }
            Map<String, String> map = tokenManagerDao.findByToken(token);
            if (null != map && map.size() != 0) {
                String data = map.get("data");
                if (!StringUtil.isEmpty(data)) {
                    safeAuditEntity.setUsername(new SM4JSUtil().decode(data));
                }
            }

            //1.默认为业务业务
            if (0 == safeAuditEntity.getEvent_type()) {
                safeAuditEntity.setEvent_type(EventTypeEnum.BUSINESS.getCode());
            }
            //2，默认异常
            if (0 == safeAuditEntity.getEvent_state()) {
                safeAuditEntity.setEvent_state(EventStateEnum.Exception_1.getCode());
            }
            //3.默认失败
            if (0 == safeAuditEntity.getEvent_result()) {
                safeAuditEntity.setEvent_result(EventResultEnum.FAIL.getCode());
            }
            //处理数据
            handleEventState(safeAuditEntity);
            return true;
        } catch (Exception e) {
            return true;
        }
    }


    @Override
    public boolean insertSysSafeSystemException(SysSafeAuditEntity safeAuditEntity, String token) {
        try {
            String userIp = Constant.USER_IP_KEY.get();
            if (!StringUtil.isEmpty(userIp)) {
                safeAuditEntity.setIp(userIp);
            }
            Map<String, String> map = tokenManagerDao.findByToken(token);
            if (null != map && map.size() != 0) {
                String data = map.get("data");
                if (!StringUtil.isEmpty(data)) {
                    safeAuditEntity.setUsername(new SM4JSUtil().decode(data));
                }
            }
            //当审计出现异常时处理
            safeAuditEntity.setEvent_type(EventTypeEnum.SYSTEM.getCode());
            //2，默认异常(默认严重)
            safeAuditEntity.setEvent_state(6);
            //3.默认失败
            safeAuditEntity.setEvent_result(EventResultEnum.FAIL.getCode());
            //4.菜单
            safeAuditEntity.setMenu_url("系统");
            //5.ip
            safeAuditEntity.setIp(userIp);
            //6.登录失效或者越权判断
            if(safeAuditEntity.getEvent_desc().contains("越权")){
                safeAuditEntity.setOpera_type(11);
            }else if(safeAuditEntity.getEvent_desc().contains("容量")){
                safeAuditEntity.setOpera_type(12);
            }else {
                safeAuditEntity.setOpera_type(13);
            }
            //处理数据
            handleEventState(safeAuditEntity);
            return true;
        } catch (Exception e) {
            return true;
        }
    }


    @Override
    public SafeAuditReply querySafes(SafeAuditRequest request) {
        SafeAuditReply.Builder builder = SafeAuditReply.newBuilder();
        //校验时间
        if (null != request.getStartDate() && null != request.getEndDate()) {
            boolean startDate = DateUtil.validDateTimeEffecitive(request.getStartDate());
            boolean endDate = DateUtil.validDateTimeEffecitive(request.getEndDate());
            if (!startDate || !endDate) {
                return builder.setErrCode(Error.FAILED.getCode())
                    .setErrMsg("时间格式有误").build();
            }
        }
        //通过操作员判断审计数据类型
        SysSafeAuditEntity safe = new SysSafeAuditEntity();
        safe.setStartTime(DateUtil.stringToDate(request.getStartDate()));
        safe.setEndTime(DateUtil.stringToDate(request.getEndDate()));
        safe.setEvent_type(request.getEventType());
        if (!StringUtil.isEmpty(request.getUsername())) {
            boolean pattern = PatternUtils.isSpecialChar(request.getUsername());
            if (pattern) {
                builder.setErrCode(CommonErrEnum.PARAM_NOT_RIGHT.getCode()).setErrMsg(CommonErrEnum.PARAM_NOT_RIGHT.getMessage());
                return builder.build();
            }
            safe.setUsername(request.getUsername());
        }
        //当页数为零时默认为1
        if (1 > request.getPageNumber()) {
            safe.setPageNumber(1);
        } else {
            safe.setPageNumber(request.getPageNumber());
        }
        //当页个数为零时默认为10
        if (0 == request.getPageCount()) {
            safe.setPageCount(10);
        } else {
            safe.setPageCount(request.getPageCount());
        }
        safe.setEvent_state(request.getEventState());
        safe.setOrder(request.getOrder());
        safe.setDesc(request.getDesc());
        safe.setOpera_type(request.getOperaType());
        List<SysSafeAuditEntity> sysSafeAuditEntities = sysSafeDAO.selectSysSafe(safe);
        int safesCount = sysSafeDAO.selectSafeCount(safe);
        if (CollectionUtils.isEmpty(sysSafeAuditEntities)) {
            builder.setErrCode(ResultEnum.SUCCESS.getCode());
            builder.setErrMsg(ResultEnum.SUCCESS.getMessage());
            return builder.build();
        }
        /**进行统计*/
        for (SysSafeAuditEntity entity : sysSafeAuditEntities) {
            SafeAuditEntity.Builder safeEntity = SafeAuditEntity.newBuilder();
            safeEntity.setCollectTime(DateUtil.dateToString(entity.getCollect_time()));
            if (!StringUtil.isEmpty(entity.getEvent_desc())) {
                safeEntity.setEventDesc(entity.getEvent_desc());
            }
            safeEntity.setEventResult(entity.getEvent_result());
            safeEntity.setEventType(entity.getEvent_type());
            safeEntity.setEventState(entity.getEvent_state());
            if (!StringUtil.isEmpty(entity.getIp())) {
                safeEntity.setIp(entity.getIp());
            }
            if (!StringUtil.isEmpty(entity.getUsername())) {
                safeEntity.setUsername(entity.getUsername());
            }
            safeEntity.setId(entity.getId());
            if(!StringUtil.isEmpty(entity.getMenu_url())){
                safeEntity.setMenuUrl(entity.getMenu_url());
            }
            safeEntity.setOperaType(entity.getOpera_type());
            builder.addData(safeEntity);
        }
        builder.setTotalPages(safesCount);
        builder.setPageNumber(request.getPageNumber());
        builder.setErrCode(ResultEnum.SUCCESS.getCode());
        builder.setErrMsg(ResultEnum.SUCCESS.getMessage());
        return builder.build();
    }

    @Override
    public SafeDTOReply queryExceptionSafes(SafeDTORequest request) {
        SafeDTOReply.Builder builder = SafeDTOReply.newBuilder();
        SafeDTORequest.Builder safeDto = SafeDTORequest.newBuilder();
        SafeDTO safe = new SafeDTO();

        SafeDTO safeDTO = sysSafeDAO.selectExecSafes(safe);
        if (null != safeDTO) {
            if (null != safeDTO.getStartTime()) {
                safeDto.setStartTime(DateUtil.dateToString(safeDTO.getStartTime()));
            }
            if (null != safeDTO.getEndTime()) {
                safeDto.setEndTime(DateUtil.dateToString(safeDTO.getEndTime()));
            }
            if (0 != safeDTO.getCount()) {
                safeDto.setCount(safeDTO.getCount());
            }
        }
        if (null != safeDto) {
            builder.setData(safeDto);
        }
        builder.setErrCode(Error.SUCCESS.getCode()).setErrMsg(Error.SUCCESS.getMessage());
        return builder.build();
    }

    @Override
    public SafeDTOReply updateExcePush(SafeDTORequest request) {
        SafeDTOReply.Builder builder = SafeDTOReply.newBuilder();
        /**参数检验*/
        if (request == null || StringUtil.isEmpty(request.getStartTime()) || StringUtil.isEmpty(request.getEndTime())) {
            builder.setErrCode(CommonErrEnum.PARAM_ERROR.getCode())
                .setErrMsg(CommonErrEnum.PARAM_ERROR.getMessage());
            return builder.build();
        }
        SafeDTO safeDTO = new SafeDTO();
        safeDTO.setStartTime(DateUtil.stringToDate(request.getStartTime()));
        safeDTO.setEndTime(DateUtil.stringToDate(request.getEndTime()));
        sysSafeDAO.updateSafePush(safeDTO);
        return builder.setErrCode(Error.SUCCESS.getCode()).setErrMsg(Error.SUCCESS.getMessage()).build();
    }

    @Override
    public SafeVolumeReply getSafeVolume(SafeAuditRequest request) {
        SafeVolume.Builder builder = SafeVolume.newBuilder();
        int safeDataMax = 1;
        //获取容量
        Map<String, String> safeCapacity = sysSafeDAO.findSafeCapacity();
        if (null == safeCapacity || safeCapacity.size() == 0) {
           safeDataMax = 1;
        }else {
            safeDataMax = Integer.parseInt(safeCapacity.get("capacity"));
        }
        SafeVolumeReply.Builder reply = SafeVolumeReply.newBuilder();

        logger.info("审计存储大小为:{}G",safeDataMax);
        double safeDataSize = 0;
        Map<String, String> map = sysSafeDAO.qyerySafeData();
        if (StringUtil.isEmpty(map.get("dataSize")) || StringUtil.isEmpty(map.get("indexSize"))) {
            builder.setVolume(SafeVolumeEnum.NOT_OVERFLOW.getCode());
            return reply.setData(builder.build()).build();
        }
        safeDataSize = Double.parseDouble(map.get("dataSize")) + Double.parseDouble(map.get("indexSize"));
        //判断审计数量是否达到了设定的溢出值 ，若溢出给前端一个提示溢出
        StringBuilder result = new StringBuilder();
        if (safeDataMax *1024* 0.8 < safeDataSize && safeDataMax*1024 > safeDataSize) {
            count++;
            builder.setVolume(SafeVolumeEnum.OVERFLOW.getCode());
            result.append(" 审计容量已超过审计容量的80%,请及时处理");
            reply.setErrCode(965);
            if(count%1000 == 1){
                insertSysSafeSystemException(new SysSafeAuditEntity("审计容量已超过审计容量的80%,请及时处理"),"ooooooooo");
            }
        } else if (safeDataMax*1024 <= safeDataSize) {
            countOver++;
            builder.setVolume(SafeVolumeEnum.OVERFLOW.getCode());
            result.append(" 审计容量已达到容量上限,请紧急处理");
            reply.setErrCode(966);
            if(countOver%1000 == 1){
                insertSysSafeSystemException(new SysSafeAuditEntity("审计容量已达到容量上限,请紧急处理"),"ooooo");
            }
        } else {
            builder.setVolume(SafeVolumeEnum.NOT_OVERFLOW.getCode());
            result.append(" 审计容量正常");
            countOver = 0;
            count = 0;
        }
        return reply.setData(builder.build()).setErrMsg(result.toString()).build();
    }

    /**
     * 导入安全审计数据
     *
     * @param request
     * @return
     */
    @Override
    @Transactional
    public ImportSafeReply importSafes(ImportSafeRequest request) {
        ImportSafeReply.Builder builder = ImportSafeReply.newBuilder();
        if (CollectionUtils.isEmpty(request.getSafesList())) {
            return builder.setErrCode(Error.SUCCESS.getCode())
                .setErrMsg(Error.SUCCESS.getMessage()).build();
        }
        int totalCount = 0;
        List<SafeAuditEntity> safesList = request.getSafesList();
        List<List<SafeAuditEntity>> lists = SplitUtils.splitList(safesList, 500);
        for (List<SafeAuditEntity> safes : lists) {
            for (SafeAuditEntity safe : safes) {
                //参数校验
                //1.时间检验
                if (!DateUtil.validDateTimeEffecitive(safe.getCollectTime())) {
                    return builder.setErrCode(630)
                        .setErrMsg("日期格式应为[yyyy-MM-dd hh-mm-ss]").build();
                }
                //2.描述校验
                if (StringUtil.isEmpty(safe.getEventDesc())) {
                    return builder.setErrCode(631)
                        .setErrMsg("事件描述不能为空").build();
                }
                //3.ip校验
                if (!IpUtils.regIp(safe.getIp())) {
                    return builder.setErrCode(632)
                        .setErrMsg("ip格式不对").build();
                }
                //4.事件类型校验
                if (safe.getEventType() != 1 && safe.getEventType() != 2) {
                    return builder.setErrCode(633)
                        .setErrMsg("事件类型只有[1,2] 两种类型").build();
                }
                //5.事件结果校验
                if (safe.getEventResult() != 1 && safe.getEventResult() != 2) {
                    return builder.setErrCode(634)
                        .setErrMsg("事件结果只有[1,2] 两种类型").build();
                }
                //6.用户名校验
                if (StringUtil.isEmpty(safe.getUsername()) || PatternUtils.isSpecialChar(safe.getUsername())) {
                    return builder.setErrCode(635)
                        .setErrMsg("用户名不能为空或特殊字符").build();
                }
                //7.事件状态校验
                if (safe.getEventState() != 1 && safe.getEventState() != 2 && safe.getEventState() != 3) {
                    return builder.setErrCode(636)
                        .setErrMsg("事件状态只有[1 ,2 ,3] 三种状态").build();
                }
            }
            int count = sysSafeDAO.importSysSafes(safes);
            totalCount = totalCount + count;
        }
        return builder.setErrCode(Error.SUCCESS.getCode())
            .setErrMsg(Error.SUCCESS.getMessage())
            .setCount(totalCount)
            .build();
    }

    /**
     * 导出安全审计数据
     *
     * @param request
     * @return
     */
    @Override
    public SafeAuditReply outputSafes(SafeAuditRequest request) {
        //通过操作员判断审计数据类型
        SafeAuditReply.Builder builder = SafeAuditReply.newBuilder();
        boolean b = DateUtil.validDateTimeEffecitive(request.getStartDate());
        boolean b1 = DateUtil.validDateTimeEffecitive(request.getEndDate());
        if (!b || !b1) {
            builder.setErrCode(636)
                .setErrMsg("时间格式有误或者时间为空")
                .build();
            return builder.build();
        }
        Date startDate = DateUtil.stringToDate(request.getStartDate());
        Date endDate = DateUtil.stringToDate(request.getEndDate());

        SysSafeAuditEntity safe = new SysSafeAuditEntity();
        safe.setStartTime(startDate);
        safe.setEndTime(endDate);
        safe.setEvent_type(EventTypeEnum.BUSINESS.getCode());

        if (!StringUtil.isEmpty(request.getUsername())) {
            boolean pattern = PatternUtils.isSpecialChar(request.getUsername());
            if (!pattern) {
                builder.setErrCode(CommonErrEnum.PARAM_NOT_RIGHT.getCode()).setErrMsg(CommonErrEnum.PARAM_NOT_RIGHT.getMessage());
                return builder.build();
            }
            safe.setUsername(request.getUsername());
        }
        safe.setEvent_state(request.getEventState());

        List<SysSafeAuditEntity> sysSafeAuditEntities = sysSafeDAO.outputSysSafes(safe);
        if (CollectionUtils.isEmpty(sysSafeAuditEntities)) {
            builder.setErrCode(ResultEnum.SUCCESS.getCode());
            builder.setErrMsg(ResultEnum.SUCCESS.getMessage());
            return builder.build();
        }
        /**进行统计*/
        for (SysSafeAuditEntity entity : sysSafeAuditEntities) {
            if(entity.getOpera_type() == 11 || entity.getOpera_type() == 12){
                continue;
            }
            SafeAuditEntity.Builder safeEntity = SafeAuditEntity.newBuilder();
            if (null != entity.getCollect_time()) {
                safeEntity.setCollectTime(DateUtil.dateToString(entity.getCollect_time()));
            }
            if (!StringUtil.isEmpty(entity.getEvent_desc())) {
                safeEntity.setEventDesc(entity.getEvent_desc());
            }
            safeEntity.setEventResult(entity.getEvent_result());
            safeEntity.setEventType(entity.getEvent_type());
            safeEntity.setEventState(entity.getEvent_state());
            if (!StringUtil.isEmpty(entity.getIp())) {
                safeEntity.setIp(entity.getIp());
            }
            if (!StringUtil.isEmpty(entity.getUsername())) {
                safeEntity.setUsername(entity.getUsername());
            }
            if(!StringUtil.isEmpty(entity.getMenu_url())){
                safeEntity.setMenuUrl(entity.getMenu_url());
            }
            safeEntity.setOperaType(entity.getOpera_type());
            safeEntity.setId(entity.getId());
            builder.addData(safeEntity);
        }
        builder.setErrCode(ResultEnum.SUCCESS.getCode());
        builder.setErrMsg(ResultEnum.SUCCESS.getMessage());
        return builder.build();
    }

    /**
     * 安全审计报表
     *
     * @param request
     * @return
     */
    @Override
    public ReportSafeReply reportSafes(SafeDTORequest request) {
        //通过操作员判断审计数据类型
        ReportSafeReply.Builder builder = ReportSafeReply.newBuilder();
        SysSafeAuditEntity safe = new SysSafeAuditEntity();
        if(StringUtil.isEmpty(request.getStartTime()) || StringUtil.isEmpty(request.getEndTime())){
            return builder.setErrCode(633)
                .setErrMsg("时间不能为空")
                .build();
        }
        safe.setStartTime(DateUtil.stringToDate(request.getStartTime()));
        safe.setEndTime(DateUtil.stringToDate(request.getEndTime()));
        if(StringUtil.isEmpty(request.getEventType())){
            safe.setEvent_type(0);
        }else {
            safe.setEvent_type(Integer.parseInt(request.getEventType()));
        }
        if(!StringUtil.isEmpty(request.getUsername())){
            safe.setUsername(request.getUsername());
        }
        return report(safe);
    }

    @Override
    public FindSafeCapacityReply findSafeCapacity(FindSafeCapacityRequest request) {
        FindSafeCapacityReply.Builder builder = FindSafeCapacityReply.newBuilder();
        Map<String, String> safeCapacity = sysSafeDAO.findSafeCapacity();
        if (null == safeCapacity || safeCapacity.size() == 0) {
           return builder.setData(1).setErrCode(Error.SUCCESS.getCode()).setErrMsg(Error.SUCCESS.getMessage()).build();
        }
        String capacity = safeCapacity.get("capacity");
        if (StringUtil.isEmpty(capacity)) {
            return builder.setData(1).setErrCode(Error.SUCCESS.getCode()).setErrMsg(Error.SUCCESS.getMessage()).build();
        }
        return builder.setData(Integer.valueOf(capacity)).setErrCode(Error.SUCCESS.getCode()).setErrMsg(Error.SUCCESS.getMessage()).build();
    }

    @Override
    public UpdateSafeCapacityReply updateSafeCapacity(UpdateSafeCapacityRequest request) {
        UpdateSafeCapacityReply.Builder builder = UpdateSafeCapacityReply.newBuilder();
        int capacity = request.getCapacity();
        if (capacity <= 0) {
            capacity = 1;
        }
        boolean result = sysSafeDAO.updateSafeCapacity(capacity);
        if (!result) {
            return builder.setErrCode(Error.FAILED.getCode()).setErrMsg(Error.FAILED.getMessage()).build();
        }
        return builder.setErrCode(Error.SUCCESS.getCode()).setErrMsg(Error.SUCCESS.getMessage()).build();
    }

    /**
     * 获取审计报表
     * @param safe
     * @return
     */
    private ReportSafeReply report(SysSafeAuditEntity safe) {
        ReportSafeReply.Builder builder = ReportSafeReply.newBuilder();
        List<SafeDataDTO> safes = sysSafeDAO.safeReport(safe);
        if(CollectionUtils.isEmpty(safes)){
            return builder.setErrCode(Error.SUCCESS.getCode())
                .setErrMsg(Error.SUCCESS.getMessage())
                .build();
        }
        for (SafeDataDTO safeData : safes){
            SafeDataResult.Builder result = SafeDataResult.newBuilder();

            if(!StringUtil.isEmpty(safeData.getUsername())){
                result.setUsername(safeData.getUsername());
            }
            result.setBusLogCount(safeData.getBusLogCount());
            result.setSysLogCount(safeData.getSysLogCount());
            result.setOutLogCount(safeData.getOutLogCount());
            result.setLoginLogCount(safeData.getLoginLogCount());
            result.setExportLogCount(safeData.getExportLogCount());
            result.setImportLogCount(safeData.getImportLogCount());
            result.setSearchLogCount(safeData.getSearchLogCount());
            result.setUpdateLogCount(safeData.getUpdateLogCount());
            result.setDeleteLogCount(safeData.getDeleteLogCount());
            result.setAddLogCount(safeData.getAddLogCount());
            result.setTotleCount(safeData.getTotleCount());
            result.setBeyond(safeData.getBeyond());
            builder.addData(result);
        }
        return builder.setErrCode(Error.SUCCESS.getCode())
            .setErrMsg(Error.SUCCESS.getMessage())
            .build();
    }





    private <T> Map<Integer, List<T>> getCurrentPageNum2Content(List<T> list, int pageSize, int pageNum) {
        if (pageSize < 0 || pageNum < 0) {
            throw new IllegalArgumentException("wrong argument: pageSize:" + pageSize + ",pageNum:" + pageNum);
        }
        Map<Integer, List<T>> ret = new HashMap<>();
        if (list == null) {
            list = new ArrayList<>();
        }
        if (list.size() == 0) {
            ret.put(1, list);
            return ret;
        }
        //如果不传pageSize或pageNum，则返回全部列表，当前页为1
        if (pageSize == 0 || pageNum == 0) {
            ret.put(1, list);
            return ret;
        }
        //智能分页指针定位
        int size = list.size();
        int start = (pageNum - 1) * pageSize;//start Index: include
        while (start >= size) {
            pageNum--;
            start -= pageSize;
        }
        int end = start + pageSize;//end index : exclude
        if (end > size) {
            end = size;
        }
        ret.put(pageNum, list.subList(start, end));
        return ret;
    }

    @Override
    public ModifyAlertEmailPropertiesReply modifyAlertEmailProperties(ModifyAlertEmailPropertiesRequest request) {
        ModifyAlertEmailPropertiesReply.Builder builder = ModifyAlertEmailPropertiesReply.newBuilder();
        if(StringUtils.isBlank(request.getReceiver())){
            return builder.setErrCode(UserErrorEnum.RECIPIENT_NOT_NULL.getCode()).setErrMsg(UserErrorEnum.RECIPIENT_NOT_NULL.getMsg()).build();
        }else if(!EmailUtil.verificationEmail(request.getReceiver())){
            return builder.setErrCode(UserErrorEnum.EMAIL_INVALID_ERROR.getCode()).setErrMsg(UserErrorEnum.EMAIL_INVALID_ERROR.getMsg()).build();
        }

        if(StringUtils.isBlank(request.getSender())){
            return builder.setErrCode(UserErrorEnum.SENDER_NOT_NULL.getCode()).setErrMsg(UserErrorEnum.SENDER_NOT_NULL.getMsg()).build();
        }else if(!EmailUtil.verificationEmail(request.getSender())){
            return builder.setErrCode(UserErrorEnum.EMAIL_INVALID_ERROR.getCode()).setErrMsg(UserErrorEnum.EMAIL_INVALID_ERROR.getMsg()).build();
        }

        if(StringUtils.isBlank(request.getUseSSL())){
            return builder.setErrCode(UserErrorEnum.CERTIFIED_SSL_NOT_NULL.getCode()).setErrMsg(UserErrorEnum.CERTIFIED_SSL_NOT_NULL.getMsg()).build();
        }
        if(StringUtils.isBlank(request.getUseTLS())){
            return builder.setErrCode(UserErrorEnum.CERTIFIED_TLS_NOT_NULL.getCode()).setErrMsg(UserErrorEnum.CERTIFIED_TLS_NOT_NULL.getMsg()).build();
        }
        //验证ip 地址
        if(StringUtils.isNotBlank(request.getHost())){
            if(!IPUtil.verificationIP(request.getHost())){
                return builder.setErrCode(UserErrorEnum.IP_FORMAT_WRONG.getCode()).setErrMsg(UserErrorEnum.IP_FORMAT_WRONG.getMsg()).build();
            }

        }
        //验证端口
        if(StringUtils.isNotBlank(request.getPort())){
            try {
                if(request.getPort().length()>6||Integer.valueOf(request.getPort())<0){
                    return builder.setErrCode(UserErrorEnum.PORT_ERROR.getCode()).setErrMsg(UserErrorEnum.PORT_ERROR.getMsg()).build();
                }
            } catch (NumberFormatException e) {
                return builder.setErrCode(UserErrorEnum.PORT_ERROR.getCode()).setErrMsg(UserErrorEnum.PORT_ERROR.getMsg()).build();
            }
        }
        Map<String,String> map = new HashMap();
        map.put("id","1");
        map.put("host",request.getHost());
        map.put("port",request.getPort());
        map.put("use_ssl",request.getUseSSL());
        map.put("use_tls",request.getUseTLS());
        map.put("username",request.getSender());
        map.put("pd_sender",request.getPdSender());
        map.put("sender",request.getSender());
        map.put("receiver",request.getReceiver());
        try {
            if(airDAO.replaceInsert(map,"email_properties_config")){
                builder.setErrCode(Error.SUCCESS.getCode()).setErrMsg(Error.SUCCESS.getMessage());
            }else{
                builder.setErrCode(Error.FAILED.getCode()).setErrMsg(Error.FAILED.getMessage());
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return builder.build();
    }


    @Override
    public AlertEmailPropertiesReply getAlertEmailProperties(AlertEmailPropertiesRequest request) {
        AlertEmailPropertiesReply.Builder builder = AlertEmailPropertiesReply.newBuilder();
        EmailPropertiesConfig emailPropertiesConfig = airDAO.getEmailPropertiesConfig("1");
        if(emailPropertiesConfig ==null || emailPropertiesConfig.equals("")){
            builder.setErrCode(Error.SUCCESS.getCode()).setErrMsg(Error.SUCCESS.getMessage());
        }else{
            AlertEmailPropertiesReply.Data.Builder replyData =AlertEmailPropertiesReply.Data.newBuilder();
            replyData.setHost(emailPropertiesConfig.getHost());
            replyData.setPort(emailPropertiesConfig.getPort());
            replyData.setUseSSL(emailPropertiesConfig.getUse_ssl());
            replyData.setUseTLS(emailPropertiesConfig.getUse_tls());
            replyData.setUsername(emailPropertiesConfig.getUsername());
            replyData.setPdSender("");
            replyData.setSender(emailPropertiesConfig.getSender());
            replyData.setReceiver(emailPropertiesConfig.getReceiver());
            builder.setErrCode(Error.SUCCESS.getCode()).setErrMsg(Error.SUCCESS.getMessage()).setData(replyData);
        }
        return builder.build();
    }

    @Override
    public String getName(String token){
        try {
            Map<String, String> map = tokenManagerDao.findByToken(token);
            if (null != map && map.size() != 0) {
                String data = map.get("data");
                if (!StringUtil.isEmpty(data)) {
                    return new SM4JSUtil().decode(data);
                }
            }
            return null;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }

    }

    private void handleEventState(SysSafeAuditEntity request) {
        try {
            ThreadPoolUtil.execute(new Runnable() {
                @Override
                public void run() {
                    //异常处理(发邮箱)
                    if (3 != request.getEvent_state()) {
                        logger.info("发送邮件：{} 操作类型：{}",request.getEvent_desc(),request.getOpera_type());
                        StringBuffer desc = new StringBuffer();
                        desc.append("异常通知:用户:[").append(request.getUsername()).append("] 在")
                            .append("时间为：[").append(DateUtil.dateToString(new Date())).append("]").append("出现了异常")
                            .append("   异常描述为：[").append(request.getEvent_desc()).append("]");
                        if(request.getOpera_type() == 11){
                            MailSendUtil.send(IscMailBuilder.builder("越权访问警告",desc.toString()));
                        }else if(request.getOpera_type() == 12){
                            MailSendUtil.send(IscMailBuilder.builder("容量溢出警告",desc.toString()));
                        }else {
                            MailSendUtil.send(IscMailBuilder.builder("异常警告",desc.toString()));
                        }
                    }
                }
            });

            ThreadPoolUtil.execute(new Runnable() {
                @Override
                public void run() {
                    sysSafeDAO.insertSysSafe(request);
                }
            });
        }catch (Exception e){

        }
    }

}
